package utils;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import pojo.FileItem;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件工具类
 */
public class FileUtils {

    //IP
    public static final String IP="127.0.0.1";
    //网络终端端口
    public static final int PORT=3333;
    public static final String UPLOAD_DIR="F:\\JavaSE\\项目实战\\UpLoad";
    //客户端下载目录
    public static final String DOWNLOAD_DIR="F:\\JavaSE\\项目实战\\DownLoad";
    //命令类型依次是：登录，查询，上传，下载，删除
    public static final int TYPE_LOGIN=1;
    public static final int TYPE_LIST=2;
    public static final int TYPE_UPLOAD=3;
    public static final int TYPE_DOWNLOAD=4;
    public static final int TYPE_DELETE=5;
    /**
     *
     * 获得上传文件路径
     * @return List
     */
    public static List<FileItem> getUploadFiles(){

        File file = new File(UPLOAD_DIR);

        //判断上传目录是否存在
        if(!file.exists()){
            //创建目录
            file.mkdir();
        }

        //将文件转换成我们自己定义的文件类
        File[] files = file.listFiles();
        List<FileItem> list = new ArrayList();
        for (int i = 0; i <files.length ; i++) {
            File f=files[i];
            if(f.isFile()){
                //id 文件名 文件路径 长度
                FileItem fileItem = new FileItem(i+1L,f.getName(),f.getAbsolutePath(),f.length());
                list.add(fileItem);
            }
        }
        return list;
    }

    /**
     * 集合转化为JSON
     * @param fileItems
     * @return
     */

    public static String listToJSON(List<FileItem> fileItems){
        return new Gson().toJson(fileItems);
    }

    /**
     * JSON转化为集合
     * @param json
     * @return
     */

    public static List<FileItem> jsonToList(String json){
        return new Gson().fromJson(json,new TypeToken<List<FileItem>>(){}.getType());
    }

    /**
     *
     * 读取字节码文件
     * @param in
     * @param out
     * @throws IOException
     */
    public static void io(InputStream in, OutputStream out) throws IOException {
        byte[] buff=new byte[1024];
        int len=0;
        //从输入流读取字节
        while((len=in.read(buff)) != -1){
            //将字节写入到输出流
            out.write(buff,0,len);
        }
        in.close();
        out.close();
    }
    public static void main(String[] args) {

        List<FileItem> uploadFiles = FileUtils.getUploadFiles();
        String s = FileUtils.listToJSON(uploadFiles);
        System.out.println(s);
        List<FileItem> list = FileUtils.jsonToList(s);
        System.out.println(list);

    }
}
